<template>
  <div>
    <el-card class="search-card">
      <BasicForm
        ref="formData"
        defaultExpandStatus
        formItemWidth="130px"
        :formColumns="formItems"
        :dataSource="formData"
        :handleSearchForm="handleQueryForm"
        @getFormData="getFormData"
      />
    </el-card>
    <el-card class="table-card">
      <skus-table
        ref="skusTable"
        showSelectCol
        showPagination
        :tableHeight="480"
        :actionColWidth="200"
        :defaultMinWidth="100"
        :dataSource="TableInfo.list"
        :columns="TableInfo.columns"
        :loading="TableInfo.loading"
        :pageSizes="pageSizes"
        :pagination="pagination"
        :total="pagination.total"
        :selectionChange="TableInfo.setSelection"
        @pageChange="handlePageChange"
        @pageSizeSelect="handlePageSizeChange"
      >
        <!-- 按钮操作栏 -->
        <BtnRender slot="content_context" :render="renderBtnsBar" />
      </skus-table>
    </el-card>
  </div>
</template>
<script>
import BasicForm from '@/components/BasicForm';
import SkusTable from '@/components/skusTable';
import BtnRender from '@/components/JSXRender/BtnRender';
import { getListPageBtnsBar } from '@/utils/getBtnsRender';
import { FORM_ITEMS, TABLE_COLUMNS, SESSION_KEY, DEV_STATUS_VALUES } from './constants';
import skusPage from '@/mixins/commodity/skusPage';
import { getInitFormData, TableInfo } from '@/utils/getUtils';
import {
  createExcelByExport,
  generateUuid,
  setAuthBtnId,
  isResponseSuccess
} from '@/utils/bizUtils';
import {
  getPagerService,
  notDevelopService,
  cancelFromReqService,
  industryExportService,
  industryImportUrl,
  devReqDetailExportService
} from '@/api/commodity/developmentRequirementPlan/developRequirementPool';
export default {
  mixins: [skusPage],
  components: {
    BasicForm,
    SkusTable,
    BtnRender,
  },
  data () {
    return {
      formItems: FORM_ITEMS,
      formData: getInitFormData(FORM_ITEMS),
      TableInfo: new TableInfo({ columns: TABLE_COLUMNS }),
      btnLoading: {
        batchUp: false,
        batchOff: false,
        changeOffTime: false,
        exportIndustry: false,
        importIndustry: false
      },
      pageSizes: [10, 100, 1000]
    }
  },
  mounted () {
    this.updateTableColumns()
    this.executeToDoTask()
    this.getTableData()
  },
  methods: {
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const addDevReqBtn = { label: '新增开发需求', method: this.handleAddDevReq }
      const addDevPlanBtn = {
        label: '新增开发计划',
        method: this.handleAddDevPlan,
        disabled: this.TableInfo.isNullSelection()
      }
      const tempNotDevBtn = {
        label: '暂不开发',
        method: this.handleTempNotDev,
        disabled: this.TableInfo.isNullSelection()
      }
      const cancelDevBtn = {
        label: '取消开发',
        method: this.handleCancelDev,
        disabled: this.TableInfo.isNullSelection()
      }
      const exportIndustryBtn = {
        label: '行业导出',
        loading: this.btnLoading.exportIndustry,
        method: this.handleExportIndustry,
      }
      const importIndustryBtn = {
        label: '行业导入',
        isImport: true,
        action: industryImportUrl,
        loading: this.btnLoading.importIndustry,
        loadingFn: state => { this.btnLoading.importIndustry = state }
      }
      const exportBtn = {
        label: '导出',
        method: this.handleExport,
        loading: this.btnLoading.export,
        hasAuth: true
      }
      // 按钮通用属性填充
      const btnBars = [
        addDevReqBtn, addDevPlanBtn, tempNotDevBtn,
        cancelDevBtn, exportIndustryBtn, importIndustryBtn,
        exportBtn
      ]
      return getListPageBtnsBar(h, btnBars, this.showBtn, 'start', { hasAuth: true })
    },
    // 处理代办事项
    executeToDoTask () {
      // 开发状态代办
      const toDoDevStatus = devStatus => {
        const index = this.formItems.findIndex(item => item.prop == 'devStatus')
        index > -1 && this.formItems.splice(index, 1)
        this.formData = { ...getInitFormData(this.formItems), devStatus }
      }
      // 是否重复开发代办
      const toDoIsRepeatDev = isRepeatDev => {
        const index = this.formItems.findIndex(item => item.prop == 'isRepeatDev')
        index > -1 && this.formItems.splice(index, 1)
        this.formData = { ...getInitFormData(this.formItems), isRepeatDev }
      }
      const { devStatus, isRepeatDev } = this.$route?.query
      if (devStatus) return toDoDevStatus(devStatus)
      if (isRepeatDev) return toDoIsRepeatDev(isRepeatDev)
    },
    // 获取表格数据 by 查询表单
    async getTableData () {
      setAuthBtnId('查询');
      const data = { ...this.formData, ...this.paginationParams }
      const res = await getPagerService(data, this.TableInfo.setLoading)
      if (res?.retData) {
        this.TableInfo.setList(res.retData.results)
        this.setTotalNum(res.retData.totalNum)
      }
    },
    // 新增开发需求
    handleAddDevReq () {
      this.$router.push({ name: 'developRequirementPoolAdd' })
    },
    // 新增开发计划
    handleAddDevPlan () {
      const canClickStatus = [DEV_STATUS_VALUES.ToDevelop, DEV_STATUS_VALUES.NotDevelop]
      const cannotClick = this.TableInfo.selection.some(item => !canClickStatus.includes(item.devStatus))
      if (cannotClick) return this.$message.warning('只能勾选待开发或暂不开发的需求')
      const reqDetailNos = this.TableInfo.selection.map(item => item.reqDetailNo)
      sessionStorage.setItem(SESSION_KEY, JSON.stringify(reqDetailNos))
      this.$router.push({
        name: 'developPlanAdd',
        query: { cacheKey: SESSION_KEY }
      });
    },
    // 暂不开发
    handleTempNotDev () {
      const cannotClick = this.TableInfo.selection.some(item => ![DEV_STATUS_VALUES.ToDevelop].includes(item.devStatus))
      if (cannotClick) return this.$message.warning('只能勾选待开发的需求')
      this.openNotDevMsgBox()
    },
    // 取消开发
    handleCancelDev () {
      const canClickStatus = [DEV_STATUS_VALUES.ToDevelop, DEV_STATUS_VALUES.NotDevelop]
      const cannotClick = this.TableInfo.selection.some(item => !canClickStatus.includes(item.devStatus))
      if (cannotClick) return this.$message.warning('只能勾选待开发或暂不开发的需求')
      this.openCancelDevMsgBox()
    },
    // 导出行业
    async handleExportIndustry () {
      const loadingFn = state => { this.btnLoading.exportIndustry = state }
      const res = await industryExportService({}, loadingFn)
      createExcelByExport({ excelTitle: `行业导出_${generateUuid()}`, res })
    },
    // 导出
    async handleExport () {
      setAuthBtnId('查询')
      const data = { ...this.formData }
      const loadingFn = state => { this.btnLoading.export = state }
      const res = await devReqDetailExportService(data, this.TableInfo.setLoading, loadingFn)
      createExcelByExport({ excelTitle: `开发需求池_${generateUuid()}`, res })
    },
    // 打开暂不开发弹框
    openNotDevMsgBox () {
      this.$confirm('请输入暂不开发原因', '提示', {
        showInput: true,
        beforeClose: async (action, instance, done) => {
          if (action !== 'confirm') return done()
          if (!instance?.inputValue) return this.$message.warning('暂不开发原因不能为空！')
          this.fetchNotDev(instance, done)
        },
      }).catch(() => {})
    },
    // 暂不开发请求
    async fetchNotDev (instance, done) {
      const data = {
        reqDetailNos: this.TableInfo.selection.map(item => item.reqDetailNo),
        notDevReason: instance?.inputValue
      }
      this.fetchConfirm(instance, done, [data, notDevelopService])
    },
    // 打开取消开发弹框
    openCancelDevMsgBox () {
      this.$confirm('请输入取消原因', '提示', {
        showInput: true,
        beforeClose: async (action, instance, done) => {
          if (action !== 'confirm') return done()
          if (!instance?.inputValue) return this.$message.warning('取消原因不能为空！')
          this.fetchCancelDev(instance, done)
        },
      }).catch(() => {})
    },
    // 暂不开发请求
    async fetchCancelDev (instance, done) {
      const data = {
        reqDetailNos: this.TableInfo.selection.map(item => item.reqDetailNo),
        cancelReason: instance?.inputValue
      }
      this.fetchConfirm(instance, done, [data, cancelFromReqService])
    },
    // 确认弹框请求
    async fetchConfirm (instance, done, [data, requestFn]) {
      const loadingFn = state => { instance.confirmButtonLoading = state }
      const res = await requestFn(data, loadingFn)
      if (isResponseSuccess(res)) {
        this.$message.success('操作成功')
        done()
        this.getTableData()
      }
    },
    // 更新表列
    updateTableColumns () {
      const planNoIndex = this.TableInfo.columns.findIndex(item => item.key == 'planNo')
      if (planNoIndex < 0) return
      this.TableInfo.columns[planNoIndex].render = this.getPlanNoRender()
    },
    // 获取计划单号render
    getPlanNoRender () {
      const onRouterPush = row => {
        let name = 'developPlanView'
        if (row.devStatus == DEV_STATUS_VALUES.Finished) {
          name = 'developPlanFinishView'
        }
        this.$router.push({ name, query: { planNo: row.planNo } })
      }
      const render = (h, { row }) => (
        <el-link
          type="primary"
          onClick={() => { onRouterPush(row) }}
        >{row.planNo}
        </el-link>
      )
      return render
    }
  }
}
</script>
